package com.community.web.master.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.common.properties.JwtProperties;
import com.community.common.utils.JwtUtil;
import com.community.model.entity.Goods;
import com.community.model.entity.RoleUser;
import com.community.model.entity.User;
import com.community.web.master.context.BaseContext;
import com.community.web.master.domain.dto.GiveRoleDto;
import com.community.web.master.domain.dto.PageUserDto;
import com.community.web.master.domain.dto.UserLoginDto;
import com.community.web.master.domain.vo.GoodsWithCategoryNameVo;
import com.community.web.master.domain.vo.PageResult;
import com.community.web.master.domain.vo.UserLoginVo;
import com.community.web.master.domain.vo.UserWithRoleVo;
import com.community.web.master.exception.DataException;
import com.community.web.master.exception.LoginFailedException;
import com.community.web.master.mapper.RoleMapper;
import com.community.web.master.mapper.RoleUserMapper;
import com.community.web.master.mapper.UserMapper;
import com.community.web.master.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 李晶
 * @since 2024-07-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleUserMapper roleUserMapper;
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public UserLoginVo login(UserLoginDto userLoginDto, HttpServletRequest request) {
        //账号是否存在?
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone", userLoginDto.getPhone()));
        if(user==null) throw new LoginFailedException("账号不存在");
        //获取加密后的密码
        String userPassword = DigestUtils.md5DigestAsHex(userLoginDto.getUserPassword().getBytes());
        //判断
        if(null==userMapper.selectOne(new QueryWrapper<User>().eq("phone", userLoginDto.getPhone()).eq("user_password",userPassword)))
            throw new LoginFailedException("密码错误");
        if(user.getUserStatus()!=1) throw new LoginFailedException("用户被冻结");
        //都通过,插入日志表
        //todo 没看见表
        String ip=request.getRemoteAddr();

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        //将userId和roleId都放进去
        RoleUser userRole = roleUserMapper.selectOne(new QueryWrapper<RoleUser>().eq("user_id", user.getId()));
        Integer roleId = userRole==null? null:userRole.getRoleId();
        claims.put("userId", user.getId());
        claims.put("roleId", roleId);//现在这个roleId是写死的,后面挪到service中查出来

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .roleId(roleId)
                .token(token)
                .build();


        return userLoginVo;
    }

    /**
     * 用户分页查询
     * @param pageUserDto
     * @return
     */
    @Override
    public PageResult pageQuery(PageUserDto pageUserDto) {
        Map<String,Object> mapTotal= new HashMap<>();
        if(pageUserDto.getUserName()!=null){
            if(!pageUserDto.getUserName().equals("")){
                mapTotal.put("user_name",pageUserDto.getUserName());
            }
        }
        if(pageUserDto.getRoleId()!=null){
            mapTotal.put("role_id",pageUserDto.getRoleId());
        }
        if(pageUserDto.getPhone()!=null){
            if(!pageUserDto.getPhone().equals("")){
                mapTotal.put("phone",pageUserDto.getPhone());
            }
        }
        Long total = userMapper.selectCountUser(mapTotal);

        Map<String,Object> map=new HashMap<>();
        map.put("limit",(pageUserDto.getPageSize()));
        map.put("offset",(pageUserDto.getPage()-1)*pageUserDto.getPageSize());
        map.put("user_name",pageUserDto.getUserName());
        map.put("role_id",pageUserDto.getRoleId());
        map.put("phone",pageUserDto.getPhone());

        List<UserWithRoleVo> result= userMapper.selectPageByMap(map);

        return new PageResult(total,result);

    }

    /**
     * 授予用户角色
     * @param giveRoleDto
     */

    @Override
    public void giveRole(GiveRoleDto giveRoleDto) {
        User user = userMapper.selectById(giveRoleDto.getId());
        if(user==null) throw new DataException("用户不存在");
        if(roleMapper.selectById(giveRoleDto.getRoleId())==null) throw new DataException("角色不存在");

        RoleUser roleUser = new RoleUser();
        roleUser.setUserId(giveRoleDto.getId());
        roleUser.setRoleId(giveRoleDto.getRoleId());
        //曾经有角色,现在更新
        RoleUser temp = roleUserMapper.selectOne(new QueryWrapper<RoleUser>().eq("user_id",giveRoleDto.getId()));
        if(temp!=null){
            roleUser.setId(temp.getId());
            roleUserMapper.updateById(roleUser);
            return;
        }
        //曾今没有,插入
        roleUserMapper.insert(roleUser);
    }
}
